import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutterstudyapplast/business/models/article_collect_item.dart';
import 'package:flutterstudyapplast/services/articlecollect/article_collect_service.dart';
import 'package:flutterstudyapplast/services/base_viewmodel.dart';
import 'package:flutterstudyapplast/services/service_locator.dart';

class ArticleCollectViewModel extends BaseViewModel with ChangeNotifier{

  ArticleCollectService _articleCollectService = serviceLocator<ArticleCollectService>();

  int _totalCount = 0;
  List<ArticleCollctItem> _collects = [];
  List<ArticleCollctItem> _websites = [];

  List<ArticleCollctItem> get collects => _collects;
  List<ArticleCollctItem> get websites => _websites;
  int get totalCount => _totalCount;

  Future<void> getCollects(int page) async{
    var result = await _articleCollectService.getArticleCollects(page);
    if(page == 0){
      _collects.clear();
    }
    _collects.addAll(result["datas"]);
    _totalCount = result["total"];
    notifyListeners();
    return null;
  }

  Future<void> getWebsites() async{
    var result = await  _articleCollectService.getWebSiteCollects();
    _websites.clear();
    _websites.addAll(result);
    notifyListeners();
    return null;
  }
  Future<ArticleCollctItem> collectWebsite(String name,String url) async{
    var result = await _articleCollectService.collectWebsite(name, url);
    if(result != null){
      if(result['errorCode'] != 0){
        return null;
      }else{
        var data = result["data"];
        return ArticleCollctItem(id:data["id"],url: data["link"],title: data["name"]);
      }
    }
    return null;
  }
  Future<bool> unCollectWebsite(int id) async{
    var result = await _articleCollectService.unCollectWebsite(id);
    if(result != null){
      if(result['errorCode'] != 0){
        return false;
      }else{
        return true;
      }
    }
    return false;
  }

  Future<bool> collectArticle(int id) async{

    var result = await _articleCollectService.collectArticle(id);
    if(result != null){
      if(result['errorCode'] != 0){
        return false;
      }else{
        return true;
      }
    }
    return false;
  }

  Future<bool> unCollectArticle(int id) async{

    var result = await _articleCollectService.unCollectArticle(id);
    if(result != null){
      if(result['errorCode'] != 0){
        return false;
      }else{
        return true;
      }
    }
    return false;
  }
  void setArticleItemCollect(item){
    _collects.removeWhere((old){

      return old.id == item.id && !item.isCollect;
    });
    print(_collects);
    notifyListeners();
  }
  void addCollectWeb(item){
    _websites.add(item);
    notifyListeners();
  }
  void removeCollectWeb(item){
    _websites.remove(item);
    notifyListeners();
  }
}